package com.ls.netty.dubborpc.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private String result;      //返回的结果
    private String param;       //客户端传入参数

    //(1)
    //创建连接成功调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //在其他方法中使用ctx
        context = ctx;

    }

    //(4)
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channelRead 被调用  ");
        result = msg.toString();
        notify();//唤醒等待的线程
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    //(3)
    //被代理对象调用,发送数据给服务器-> wait->等待被唤醒(channelRead)->返回结果
    @Override
    public synchronized Object call() throws Exception {
        System.out.println(" call1 被调用  ");

        context.writeAndFlush(param);
        //进行wait
        wait(); //等待channelRead 方法获取到服务器的结果后，唤醒
        System.out.println(" call2 被调用  ");
        return  result; //服务方返回的结果

    }
    //(2)
    void setParam(String param){
        this.param = param;
    }

}
